<template>
	<view class="">
		<uni-nav-bar :fixed="true" status-bar left-icon="plusempty" v-if="!viewState" left-text="添加权益卡" title="点击使用权益"
			@clickLeft="back" leftWidth="168rpx" style="border: none" :border="false" />
		<uni-nav-bar :fixed="true" status-bar left-icon="undo" v-else left-text="切换权益卡" title="权益使用"
			@clickLeft="changeCard" leftWidth="168rpx" style="border: none" :border="false" />
		<view class="service-container-box service-container-backimage" v-if="isWxToken && equityCardList.length > 0">
			<img src="/static/service/service-back.png" mode="" class="image-service-backimg" v-if="viewState" />
			<view class="service-list-box" v-if="!viewState">
				<view class="list-box" v-for="(item, index) in equityCardList" :key="index">
					<img :src="BASE_URL + item.equityUrfaceImage1" class="img-style" alt="" srcset="" />
					<view class="list-info">
						<view class="list-info-box">
							<text>权益名称：{{ item.equityteName }}</text>
							<text>有效期：{{
                parseTime(item.cardUseDeadLine, "{y}-{m}-{d}")
              }}</text>
						</view>

						<view class="vip-active-use-box" @tap="equityCardDetails(item)">去使用权益</view>
					</view>
				</view>
			</view>

			<view class="service-container" v-else>
				<!-- <view class="change-card-box">切换权益卡</view> -->
				<!-- 会员卡头部 -->
				<view class="membership-card">
					<swiper class="swiper-box" :autoplay="true" :interval="4000" :duration="500">
						<swiper-item>
							<img :src="BASE_URL + viewStateObject.equityUrfaceImage1" class="img-style-details" alt=""
								srcset="" />
						</swiper-item>
						<swiper-item>
							<img :src="BASE_URL + viewStateObject.equityUrfaceImage2" class="img-style-details" alt=""
								srcset="" />
						</swiper-item>
					</swiper>
				</view>

				<!-- 会员信息 -->
				<view class="member-info">
					<view class="info-title">{{ viewStateObject.equityteName
            }}<text class="card-status" @tap="viewCardDetailsLook">卡权益详情</text></view>
					<view class="info-details">
						<view class="info-row">
							<text class="label">权益人：</text>
							<text class="value">{{ viewStateObject.userName || "--" }}</text>
						</view>
						<view class="info-row">
							<text class="label">卡号：</text>
							<text class="value">{{ viewStateObject.no }}</text>
						</view>
						<view class="info-row">
							<text class="label">激活日期：</text>
							<text class="value">{{
                parseTime(viewStateObject.activeTime)
              }}</text>
						</view>
						<view class="info-row">
							<text class="label">有效期至：</text>
							<text class="value">{{
                parseTime(viewStateObject.cardUseDeadLine)
              }}</text>
						</view>
					</view>
				</view>

				<!-- 服务列表 -->
				<view class="service-list">
					<!-- 专属健康管家 -->
					<view class="service-item" v-for="(items, index) in viewStateObject.equityConfigObject" :key="index"
						@tap.stop="viewServiceDetails(items)">
						<image class="service-image" :src="BASE_URL + items.EQUITY_PARAMS_IMG" mode="aspectFill">
						</image>
						<view class="service-content">
							<view class="service-title">
								<text>{{ items.EQUITY_PARAMS_NAME }}</text>
								<text class="service-action" v-if="
                    viewStateObject.canNowUseObject[items.EQUITY_TYPE].canUse &&
                    items.EQUITY_PARAMS_SERVICE === 'FORM_SUBMIT'
                  " @tap.stop="
                    navigateToAppointment(
                      items,
                      viewStateObject.id,
                      items.EQUITY_TYPE
                    )
                  ">立即预约</text>
								<text class="service-action" v-if="
                    viewStateObject.canNowUseObject[items.EQUITY_TYPE].canUse &&
                    items.EQUITY_PARAMS_SERVICE === 'ENTERPRISE_WECHAT'
                  " @tap.stop="openKFUrl(viewStateObject.id, items.EQUITY_TYPE, viewStateObject, items)">联系客服</text>
								<text class="service-action" v-if="
                    viewStateObject.canNowUseObject[items.EQUITY_TYPE].canUse &&
                    items.EQUITY_PARAMS_SERVICE === 'SERVICE_LINK'
                  " @tap.stop="openFWUrl(items.EQUITY_SERVICE_LINK)">服务链接</text>
								<!-- <button
                  class="service-action lianxikf"
                  v-if="
                    viewStateObject.canNowUseObject[items.EQUITY_TYPE].canUse &&
                    items.EQUITY_PARAMS_SERVICE === 'ENTERPRISE_WECHAT'
                  "
                  open-type="contact"
                  bindcontact="handleContact"
                  binderror="contactError"
                >
                  联系客服
                </button> -->

								<text class="service-action service-action-waite" v-if="
                    !viewStateObject.canNowUseObject[items.EQUITY_TYPE].canUse
                  ">{{
                    parseTime(
                      viewStateObject.canNowUseObject[items.EQUITY_TYPE]
                        .limitTime,
                      "{y}-{m}-{d}"
                    )
                  }}后可使用</text>
							</view>
							<text class="service-desc">{{ items.EQUITY_PARAMS_REMARK }}</text>
							<view class="service-times" v-if="items.EQUITY_PARAMS_USETIME !== -1">
								<text class="sy-style">剩余：<text class="cs-style">{{
                    Number(items.EQUITY_PARAMS_USETIME) -
                    Number(viewStateObject.equityUseObject[items.EQUITY_TYPE])
                  }}</text>次</text>/已用{{ viewStateObject.equityUseObject[items.EQUITY_TYPE] }}次
							</view>
							<view class="service-times" v-else>
								<text class="sy-style">无限次</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="service-nodata" v-else>
			<view style="text-align: center">
				<img src="/static/service/nodata.svg" alt="" srcset="" />
			</view>
			<view class="service-nodata-text"> 暂无服务权益 </view>
		</view>

		<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
			<view class="popup-box">
				<image :src="BASE_URL + equityRightsDetails" class="popup-box-img" mode="widthFix" @error="imageError"
					v-if="equityRightsDetails"></image>
				<view class="">
					<view style="text-align: center" v-if="!equityRightsDetails">
						<img src="/static/service/nodata.svg" alt="" srcset="" />
					</view>
					<view class="service-nodata-text" v-if="!equityRightsDetails">
						暂无权益详情
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		watch,
		onMounted
	} from "vue";
	import {
		getWxToken,
		loginAuthorize,
		parseTime,
		errorStatus,
	} from "/api/hook.js";
	import {
		queryUserEquityCard,
		submitAppointment,
		BASE_URL
	} from "/api/base.js";
	import {
		onPullDownRefresh,
		onShow
	} from "@dcloudio/uni-app";
	const isWxToken = computed(() => {
		if (getWxToken()) {
			return true;
		} else {
			return false;
		}
	});
	const viewState = ref("");
	const viewStateObject = ref(null);
	const equityCardList = ref([]);
	let timer = null;
	const toActivePage = () => {
		uni.navigateTo({
			url: "/pages/activeUser/index",
		});
	};
	const loadData = async () => {
		uni.showLoading({
			title: "加载中...",
			mask: true,
		});
		// clearTimeout(timer);
		// timer = setTimeout(() => {
		// 	uni.hideLoading();
		// })
		const res = await queryUserEquityCard();
		if (res.data.state === "WX_USER_NOT_LOGIN") {
			await loginAuthorize();
			loadData();
		} else {
			uni.hideLoading();
			if (res.data.state === "SUCCESS") {
				equityCardList.value = res.data.list;
			} else {
				equityCardList.value = [];
				uni.showToast({
					title: errorStatus[res.data.state] || "查询失败",
					icon: "error",
				});
			}
		}
	};

	onPullDownRefresh(() => {
		if (!viewState.value) {
			loadData();
		}
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 1000);
	});

	const equityCardDetails = (row) => {
		viewState.value = row.id;
		viewStateObject.value = {
			...row,
			equityUseObject: JSON.parse(row.equityUse),
			equityConfigObject: JSON.parse(row.equityConfig).sort(
				(a, b) => a.EQUITY_PARAMS_SORT - b.EQUITY_PARAMS_SORT
			),
			equityUseTimeObject: JSON.parse(row.equityUseTime),
			canNowUseObject: JSON.parse(row.canNowUse),
		};
	};

	const back = () => {
		toActivePage();
	};

	const changeCard = () => {
		viewState.value = "";
		viewStateObject.value = null;
	};

	const navigateToAppointment = (serviceInfo, cardId, equityType) => {
		uni.navigateTo({
			url: "/pageA/service-details/appointmentForm",
			success: function(res) {
				// 通过eventChannel向打开页面传送数据
				res.eventChannel.emit("appointmentData", {
					serviceInfo: serviceInfo,
					cardId: cardId,
					equityType: equityType,
					equityUse: viewStateObject.value.equityUseObject,
					userName: viewStateObject.value.userName,
					cardInfo: viewStateObject.value
				});
			},
		});
	};

	const equityRightsDetails = ref("");
	const popup = ref(null);
	const viewCardDetailsLook = () => {
		popup.value.open();
		equityRightsDetails.value = viewStateObject.value.equityRightsDetails;
	};

	const imageError = (e) => {
		uni.showToast({
			title: "权益详情加载失败",
			icon: "none",
		});
	};

	// 官方客服消息回调
	const handleContact = (e) => {
		console.log("客服消息回调", e.detail);
	};

	// 客服消息错误处理
	const contactError = (e) => {
		//   this.setData({ showFallback: true });
		uni.showToast({
			title: "客服连接失败",
			icon: "none",
		});
	};

	// 打开外部网址链接
	const openFWUrl = (url) => {
		// 检查是否在微信小程序环境
		if (
			uni.getSystemInfoSync().platform === "mp-weixin" ||
			uni.getSystemInfoSync().platform === "android" ||
			uni.getSystemInfoSync().platform === "ios"
		) {
			// 使用web-view组件打开外部链接
			uni.navigateTo({
				url: `/pageA/webview/index?url=${encodeURIComponent(url)}`,
				fail: (err) => {
					uni.showToast({
						title: "打开链接失败",
						icon: "none",
					});
				},
			});
		} else {
			// 非微信环境下使用系统浏览器打开
			window.open(url, "_blank");
		}
	};

	// 打开客服链接
	const openKFUrl = async (id, type, row, item) => {
		// 提交预约信息
		let appointmentData = {
			applyContent: JSON.stringify({
				infos: [{
					label: "服务类型",
					value: "联系客服",
					type: "text"
				},{
					label: "权益类型",
					value: item.EQUITY_PARAMS_NAME,
					type: "text"
				}, {
					label: "就诊人",
					value: row.userName,
					type: "text",
				}],
				suppleInfos:[]
			}),
			equitycardId: id,
			equityType: type, //formData.value.equityType,
		};
		await submitAppointment(appointmentData);
		
		// 企业微信ID
		const corpid = "wwad4f8c3168b4cd3f";
		// 客服URL
		const customerUrl = "https://work.weixin.qq.com/kfid/kfcde45e508f03d00b0";

		// 检查是否在微信小程序环境
		if (
			uni.getSystemInfoSync().platform === "mp-weixin" ||
			uni.getSystemInfoSync().platform === "android" ||
			uni.getSystemInfoSync().platform === "ios"
		) {

			let stringsUrl = "权益人：" + row.userName + "；服务：" + item.EQUITY_PARAMS_NAME + "；卡号：" + row.no
			// 提交预约信息
			// const appointmentData = {
			//   applyContent: "联系客服",
			//   equitycardId: id,
			//   equityType: type, //formData.value.equityType,
			// };

			// const res = await submitAppointment(appointmentData);
			// console.log(res);
			// if (res.data.state === "APPLY_SUCCESS") {
			// 使用微信小程序原生API打开客服会话窗口
			wx.openCustomerServiceChat({
				extInfo: {
					url: customerUrl,
				},
				corpId: corpid,
				showMessageCard: true,
				sendMessageTitle: stringsUrl, // 可以传递自定义信息
				sendMessagePath: "/pages/index/index",
				sendMessageImg: "/static/index/index.jpg",
				success: () => {
					console.log("客服会话窗口打开成功");
				},
				fail: (err) => {
					console.error("客服会话窗口打开失败:", err);
					uni.showToast({
						title: "客服连接失败",
						icon: "none",
					});
				},
			});
			// }else {
			// 	throw new Error(errorStatus[res.data.state] || "预约失败");
			// }
		} else {
			// 非微信环境下可以使用其他方式处理
			uni.showToast({
				title: "仅支持在微信小程序中使用客服功能",
				icon: "none",
			});
		}
	};

	onMounted(() => {
		loadData();
		// 获取路由参数
		try {
			const instance = getCurrentInstance().proxy;
			const eventChannel = instance.getOpenerEventChannel();
			eventChannel.on("serviceData", function(data) {
				equityCardDetails(data.row);
			});
		} catch (error) {}
	});

	// 添加 onShow 生命周期钩子，在页面显示时刷新数据
	onShow(() => {
		console.log("Tab页面 onShow 生命周期触发");
		// 当从其他页面切换回来时，刷新数据
		loadData();
	});

	// 查看详情
	const viewServiceDetails = (row) => {
		// uni.navigateTo({
		// 	url: "/pageA/service-details/index?info=" + JSON.stringify(row)
		// });
		navigateToAppointment(row, viewStateObject.id, row.EQUITY_TYPE)
	}
</script>

<style lang="scss" scoped>
	.service-container-box {
		background-color: #f5f5f5;
	}

	.service-container {
		padding: 20rpx;
		background-color: #f5f5f5;
	}

	.membership-card {
		// background: linear-gradient(to right, #1a4f5c, #0d2d36);
		color: #fff;
		// padding: 30rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		height: 428rpx;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.price-info {
				.price-label {
					font-size: 24rpx;
				}

				.price-value {
					font-size: 36rpx;
					font-weight: bold;
					margin-left: 10rpx;
				}
			}

			.version-tag {
				background-color: rgba(255, 255, 255, 0.2);
				padding: 4rpx 16rpx;
				border-radius: 8rpx;
				font-size: 24rpx;
			}
		}

		.card-title {
			font-size: 48rpx;
			font-weight: bold;
			margin: 30rpx 0;
		}

		.benefits-list {
			.benefit-item {
				display: block;
				font-size: 24rpx;
				margin: 10rpx 0;
				color: rgba(255, 255, 255, 0.9);
			}
		}
	}

	.member-info {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;

		.info-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.card-status {
				background-color: #45b6b0;
				font-size: 24rpx;
				font-weight: normal;
				color: #fff;
				display: inline-block;
				padding: 12rpx 24rpx;
				border-radius: 56rpx;
			}
		}

		.info-details {
			.info-row {
				display: flex;
				margin: 10rpx 0;
				font-size: 28rpx;

				.label {
					color: #666;
					width: 160rpx;
				}

				.value {
					color: #333;
				}
			}
		}
	}

	.service-list {
		.service-item {
			background-color: #fff;
			padding: 20rpx;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			.service-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}

			.service-content {
				flex: 1;

				.service-title {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 10rpx;
					font-size: 32rpx;
					font-weight: bold;

					.service-action {
						background-color: #45b6b0;
						font-size: 24rpx;
						font-weight: normal;
						color: #fff;
						display: inline-block;
						padding: 12rpx 24rpx;
						border-radius: 56rpx;
					}

					.lianxikf {
						padding: 0 24rpx;
						margin: 0;
					}

					.service-action-waite {
						background-color: #aaaaaa;
					}
				}

				.service-desc {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 10rpx;
				}

				.service-times {
					font-size: 24rpx;
					color: #999;
					text-align: right;
					margin-top: 24rpx;
				}
			}
		}
	}

	.sy-style {
		font-weight: 600;
		color: #000;
	}

	.cs-style {
		font-weight: 600;
		color: #45b6b0;
	}

	.service-nodata-text {
		text-align: center;
	}

	.button-index {
		width: 80%;
		height: 112rpx;
		background-image: url("../../static/index/active.png");
		background-size: 100% 100%;
		text-align: center;
		line-height: 88rpx;
		margin: 12px auto;
	}

	.text-box {
		color: #fff;
		font-size: 40rpx;
	}

	.service-list-box {
		width: calc(100% - 40rpx);
		height: auto;
		padding: 20rpx;

		.list-box {
			width: 100%;
			height: 428rpx;
			position: relative;
			border-radius: 8rpx;
			overflow: hidden;
			margin-bottom: 24rpx;

			.img-style {
				width: 100%;
				height: 100%;
			}

			.list-info {
				background-color: rgba(255, 255, 255, 0.8);
				position: absolute;
				bottom: 0;
				left: 0;
				width: calc(100% - 48rpx);
				height: auto;
				padding: 24rpx;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.85);

				.list-info-box {
					display: flex;
					flex-flow: row nowrap;
					justify-content: space-between;
				}
			}
		}
	}

	.service-container-backimage {
		position: relative;
	}

	.image-service-backimg {
		width: 100%;
		height: 224rpx;
		position: absolute;
		top: 0;
	}

	.img-style-details {
		width: 100%;
		height: 100%;
	}

	.swiper-box {
		width: 100%;
		height: 100%;
	}

	.popup-box {
		width: 100%;
		height: 80vh;
		background-color: #fff;
		overflow: auto;
		display: flex;
		justify-content: center;
		align-items: flex-start;
		box-sizing: border-box;
	}

	.popup-box-img {
		width: 100%;
		height: auto;
	}

	.change-card-box {
		width: 200rpx;
		height: auto;
		padding: 12rpx;
		text-align: center;
		background-color: rgba(255, 255, 255, 0.68);
		color: rgba(0, 0, 0, 0.85);
		position: fixed;
		top: 12rpx;
		left: 0;
		z-index: 9999;
		border-top-right-radius: 32rpx;
		border-bottom-right-radius: 32rpx;
		font-weight: 600;
	}

	.vip-active-use-box {
		height: auto;
		padding: 16rpx 24rpx;
		border-radius: 36rpx;
		font-size: 28rpx;
		color: #fff;
		background: #45b6b0;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
	}
</style>